#include "Receiver.h"
#include "ui_Receiver.h"

Receiver::Receiver(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Receiver)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(resetsocket()));
    state=false;
}

Receiver::~Receiver()
{
    timer->stop();
    if(state==true)
        receiver->close();
    delete ui;
}

void Receiver::ReceiveImage()
{
    static uint count=1;
    static uint size=0;
    while (receiver->hasPendingDatagrams())
    {

        QByteArray data_gram;
        data_gram.resize(receiver->pendingDatagramSize());
        receiver->readDatagram(data_gram.data(),data_gram.size(),&sender_ip,&sender_port);
        PackageHeader *packagehead = (PackageHeader *)data_gram.data();
        if (packagehead->count == count)
        {
            qDebug("%d",count);
            count++;
            size+=packagehead->packet_size-packagehead->packet_header_size;
            if ((size>1024*1000)||(packagehead->package_Offset>1024*1000))
            {
                count = 1;
                size = 0;
                return;
            }
            memcpy(imageData.data+packagehead->package_Offset,data_gram.data()+packagehead->packet_header_size,packagehead->packet_size-packagehead->packet_header_size);
            if ((packagehead->packet_num==packagehead->count)&&(size==packagehead->package_size))
            {
                imageData.length = packagehead->package_size;
                QImage image;
                image.loadFromData((uchar *)imageData.data,imageData.length,"JPEG");
                QPixmap pixmap=QPixmap::fromImage(image);
                ui->label_image->setPixmap(pixmap);
                memset(&imageData,0,sizeof(UdpUnpackData));
                count=1;
                size=0;
            }
        }
        else
        {
            memset(&imageData,0,sizeof(UdpUnpackData));
            count=1;
            size=0;
        }
    }
}
void Receiver::resetsocket()
{
    if(receiver->bytesAvailable()!=0)
    {
        receiver->close ();
        receiver=new QUdpSocket(this);
        receiver->bind (ui->lineEdit_port->text().toInt(),QUdpSocket::ShareAddress);
        connect(receiver,SIGNAL(readyRead()),this,SLOT(ReceiveImage()));
    }
}
void Receiver::on_B_strat_clicked()
{
    if(state==false)
    {
        receiver=new QUdpSocket(this);
        receiver->bind(ui->lineEdit_port->text().toInt(), QUdpSocket::ShareAddress);
        connect(receiver,SIGNAL(readyRead()),this,SLOT(ReceiveImage()));
        timer->start(10);
        state=true;
    }
}

void Receiver::on_B_stop_clicked()
{
    if(state==true)
    {
        timer->stop();
        receiver->close();
        state=false;
    }
}
